
package com.mhy.soloader.so;

import android.content.Context;
import android.os.Build;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;


/**
 * 用于从assets读取资源文件，输出至指定的目录下
 */
public class AssetsSo {
    //	public static String	SoPath	= "/sdcard/sc/libs";

    /**
     * 输出assets/so目录下，ABI对应类型文件夹下的所有文件，到目录destSoPath
     */
    public static void ExportSo(Context context, String destSoPath) {

        String CPU_ABI = android.os.Build.CPU_ABI;                // x86
        String AssetSoPath = "so" + File.separator + CPU_ABI;    // assets/so/x86
        System.out.println("CPU_ABI -> " + CPU_ABI);
//        Build.SUPPORTED_ABIS
        copyFilesFromAssets(context, AssetSoPath, destSoPath);
    }

    /**
     * 从项目assets目录下复制文件夹、或文件 (assetsPath与savePath需同为目录或同为文件路径)
     */
    private static void copyFilesFromAssets(Context context, String assetsPath, String savePath) {
        try {
            String fileNames[] = context.getAssets().list(assetsPath);// 获取assets目录下的所有文件及目录名
            if (fileNames.length > 0) {// 如果是目录
                File file = new File(savePath);
                file.mkdirs();// 如果文件夹不存在，则递归
                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, assetsPath + File.separator + fileName, savePath + File.separator + fileName);
                }
            } else {// 如果是文件
                InputStream is = context.getAssets().open(assetsPath);
                FileOutputStream fos = new FileOutputStream(new File(savePath));
                byte[] buffer = new byte[1024];
                int byteCount = 0;
                while ((byteCount = is.read(buffer)) != -1) {// 循环从输入流读取
                    // buffer字节
                    fos.write(buffer, 0, byteCount);// 将读取的输入流写入到输出流
                }
                fos.flush();// 刷新缓冲区
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
